#include "stdafx.h"
#include "SDLTexture.h"
#include "ResourceLoader.h"
#include "SDL_render.h"

using namespace std;

namespace ZeEngine
{
    SDLTexture::SDLTexture(const string& strPath, const string& strName, const string& strGroup) : Resource(strPath, strName, strGroup),
                                                                                                                        m_texture(NULL), 
                                                                                                                        m_format(0),
                                                                                                                        m_access(0)
    {
    }

    SDLTexture::SDLTexture(SDL_Texture* pTexture)  : Resource("", "", ""), m_texture(pTexture), m_format(0), m_access(0)
    {
        bool fSuccess = false;

        if (m_texture)
        {
            s32 width = 0;
            s32 height = 0;

            if (SDL_QueryTexture(m_texture, &m_format, &m_access, &width, &height) < 0)
            {
                LOG_ERROR("Error querying texture: " + GetPath() + " Error: " + SDL_GetError());
            }
            else
            {
                m_dimension.Set(width, height);
                fSuccess = true;
            }
        }

        SetLoaded(fSuccess);
    }


    SDLTexture::~SDLTexture()
    {
        if (IsLoaded())
        {
            SDL_DestroyTexture(m_texture);
            m_format = 0;
            m_access = 0;
            m_dimension.Set(0,0);
            m_texture = NULL;
        }

        SetLoaded(false);
    }

    bool SDLTexture::Load(ResourceLoader& loader)
    {
        bool fSuccess = true;

        if (!IsLoaded())
        {    
            m_texture = loader.LoadTexture(GetPath());
            fSuccess = m_texture != NULL;

            if (fSuccess)
            {
                s32 width = 0;
                s32 height = 0;
                if (SDL_QueryTexture(m_texture, &m_format, &m_access, &width, &height) < 0)
                {
                    LOG_ERROR("Error querying texture: " + GetPath() + " Error: " + SDL_GetError());
                    Unload(loader);
                    fSuccess = false;
                }
                else
                {
                    m_dimension.Set(width, height);
                }
            }
            SetLoaded(fSuccess);
        }

        return fSuccess;
    }

    void SDLTexture::Unload(ResourceLoader& loader)
    {
        SetLoaded(false);

        if (IsLoaded())
        {
            loader.UnloadTexture(m_texture);
        }

        m_format = 0;
        m_access = 0;
        m_dimension.Set(0,0);
        m_texture = NULL;
    }
}